package com.qfedu.common.core.exception;

import com.qfedu.common.core.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname GlobalExceptionAdvice
 * @Description TODO
 * @Date 2025-09-23 9:08
 * @Created by 老任与码
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    // 处理验证异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidHandler(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return R.fail(message);
    }

    // 处理验证异常
    @ExceptionHandler(ConstraintViolationException.class)
    public R constraintViolationException(ConstraintViolationException ex) {
        List<String> list = new ArrayList<>();
        // 获取对应的迭代器
        Iterator<ConstraintViolation<?>> iterator = ex.getConstraintViolations().iterator();
        while (iterator.hasNext()) {
            ConstraintViolation<?> next = iterator.next();
            // 获取异常信息
            // System.out.println(next.getMessage());
            list.add(next.getMessage());
        }
        return R.fail(list.stream().collect(Collectors.joining(",")));
    }

    @ExceptionHandler(CommonException.class)
    public R commonExceptionHandler(CommonException e) {
        // 异常需要记录到日志中
        log.error(e.getMsg());
        return R.fail(e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {
        // 异常需要记录到日志中
        log.error(e.getMessage());
        e.printStackTrace();
        return R.fail("未知异常，请联系客服");
    }
}
